import os
import sys
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
from pyftpdlib.authorizers import DummyAuthorizer
import PySimpleGUI as sg
import threading


sg.theme("Default1")


def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)


def start_ftp_server(window, homedir, user, password, port):
    window['Start FTP'].update(disabled=True)
    authorizer = DummyAuthorizer()
    authorizer.add_user(user, password, homedir, perm='elradfmwMT')
    handler = FTPHandler
    handler.authorizer = authorizer
    server = FTPServer(('0.0.0.0', port), handler)
    server.serve_forever()

homedir = os.path.join(os.getcwd(), "public")
user = 'guest'
password = '123456'
port = 2121

layout = [[
    sg.FolderBrowse('Set Folder', size=(15, 3), initial_folder=homedir, target='--HOMEDIR--'),
    sg.Button('Start FTP', size=(15, 3)),
    sg.Button('QUIT', size=(15, 3))
]]


layout += [
    [sg.Text(f"Folder: ", size=(6, 1)), sg.Input(homedir, size=(45, 1), key="--HOMEDIR--", readonly=True)],
    [sg.Text(f"User: ", size=(6, 1)), sg.Input(user, size=(45, 1), key="--USER--")],
    [sg.Text(f"Password: ", size=(6, 1)), sg.Input(password, size=(45, 1), key="--PASSWORD--")],
    [sg.Text(f"Port: ", size=(6, 1)), sg.Input(port, size=(45, 1), key="--PORT--")]
]


window = sg.Window("FTP Server", layout=layout, icon=resource_path("logo.ico"))


while True:
    event, values = window.read()
    if event in (sg.WINDOW_CLOSED, 'QUIT'):
        break
    elif event == 'Start FTP':
        threading.Thread(
            target=start_ftp_server, 
            args=((window, values['--HOMEDIR--'], values['--USER--'], values['--PASSWORD--'], values['--PORT--'])), 
            daemon=True
        ).start()

window.close()